﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using CommonControl;

namespace YJY_DMZS.BasisFile
{
    public partial class FrmProduct_Editor : XtraForm
    {
        private string captionFormat;
        /// <summary>
        /// 产品ID,非整数位新增
        /// </summary>
        public long ID;

        /// <summary>
        /// 产品类型
        /// </summary>
        private DMZS.Model.ProductType ProductType;


        #region ================================初始化=====================================
        public FrmProduct_Editor()
        {
            InitializeComponent();
        }

        private void FrmProduct_Editor_Load(object sender, EventArgs e)
        {
            LoadInit();
        }

        private void FrmProduct_Editor_Shown(object sender, EventArgs e)
        {
            if (ID <= 0)
            {
                NewRecord();
            }
            else
            {
                LoadData();
            }
        }

        //enter -> tab
        protected override bool ProcessDialogKey(Keys keyData)
        {
            if (keyData == Keys.Enter && !(this.ActiveControl.Parent is ButtonEdit))
            {
                keyData = Keys.Tab;
            }

            return base.ProcessDialogKey(keyData);
        }
        #endregion ================================初始化=====================================


        #region ================================功能函数区=====================================

        /// <summary>
        /// 初始加载
        /// </summary>
        private void LoadInit()
        {
            var bll = new DMZS.BLL.UnitBase();
            var ds = new DataSet();
            try
            {
                ds = bll.GetListExpand(" (Deleted=0 or Deleted is null) ");
            }
            catch (Exception ex)
            {
                CommonControl.Utils.WriteTxtLog(ex);
                XtraMessageBox.Show(Utils.GetRuntimeMessage(ex, "加载数据出错。"), Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                Close();
                return;
            }

            if (ds == null || ds.Tables.Count <= 0)
            {
                XtraMessageBox.Show("加载单位下拉框数据出错。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                Close();
                return;
            }

            lueUnit.Properties.DataSource = ds.Tables[0];
            lueUnit1.Properties.DataSource = ds.Tables[0];
            captionFormat = Text;
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            Text = string.Format(captionFormat, "维护");

            var bll = new DMZS.BLL.Product();
            var row = bll.GetRecordByID(ID);
            if (row == null)
            {
                XtraMessageBox.Show("该条数据已被删除，请刷新数据。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                Close();
                return;
            }

            if (row["TypeID"] != DBNull.Value && Convert.ToInt32(row["TypeID"]) > 0)
            {
                DMZS.BLL.ProductType bll_productype = new DMZS.BLL.ProductType();
                ProductType = bll_productype.GetModel(Convert.ToInt32(row["TypeID"]));
            }
            else
            {
                ProductType = null;
            }

            bteProductTypeNo.Text = ProductType == null ? "" : ProductType.Code;
            txtCode.Text = row["Code"].ToString();
            txtName.Text = row["Name"].ToString();
            txtFullName.Text = row["FullName"].ToString();
            txtSpecification.Text = row["Specification"].ToString();
            txtModel.Text = row["Model"].ToString();
            lueUnit.EditValue = row["UnitID"];
            lueUnit1.EditValue = row["UnitID1"];
            speChangeRate.Value = Convert.ToDecimal(row["ChangeRate"]);
            chkIfStop.Checked = Convert.ToBoolean(row["IsStop"]);
            mmeRemark.Text = row["Remark"].ToString();

            bteProductTypeNo.Properties.ReadOnly = true;
            bteProductTypeNo.TabStop = false;
            bteProductTypeNo.Properties.Buttons[0].Enabled = false;
            txtCode.Properties.ReadOnly = true;
            txtName.Focus();
        }

        /// <summary>
        /// 新增
        /// </summary>
        private void NewRecord()
        {
            Text = string.Format(captionFormat, "新增");
            ID = 0;
            ProductType = null;
            bteProductTypeNo.Text = string.Empty;
            txtCode.Text = string.Empty;
            txtName.Text = string.Empty;
            txtFullName.Text = string.Empty;
            txtSpecification.Text = string.Empty;
            txtModel.Text = string.Empty;
            lueUnit.EditValue = null;
            lueUnit1.EditValue = null;
            speChangeRate.Value = 0m;
            chkIfStop.Checked = false;
            mmeRemark.Text = string.Empty;

            txtCode.Properties.ReadOnly = false;
            bteProductTypeNo.TabStop = true;
            bteProductTypeNo.Properties.ReadOnly = false;
            bteProductTypeNo.Properties.Buttons[0].Enabled = true;
            bteProductTypeNo.Focus();
        }

        /// <summary>
        /// 保存修改值
        /// </summary>
        private void SaveModify()
        {
            var bll = new DMZS.BLL.Product();
            var model = new DMZS.Model.Product();
            model.ID = ID;
            model.TypeID = ProductType == null ? 0 : ProductType.ID;
            model.Code = txtCode.Text.Trim();
            model.Name = txtName.Text.Trim();
            model.NamePY = CommonControl.StringHelper.GetFirstLetterOfChinese(model.Name, true);
            model.FullName = txtFullName.Text.Trim();
            model.Specification = txtSpecification.Text.Trim();
            model.Model = txtModel.Text.Trim();
            model.UnitID = lueUnit.EditValue == null ? 0 : Convert.ToInt32(lueUnit.EditValue);
            model.UnitID1 = lueUnit1.EditValue == null ? 0 : Convert.ToInt32(lueUnit1.EditValue);
            model.ChangeRate = speChangeRate.Value;
            model.IsStop = chkIfStop.Checked;
            model.Remark = mmeRemark.Text;

            ProcessesResult(bll.UpdateExpand(model));
        }
        /// <summary>
        /// 保存新记录
        /// </summary>
        private void SavaNew()
        {
            var bll = new DMZS.BLL.Product();
            var model = new DMZS.Model.Product();
            model.TypeID = ProductType == null ? 0 : ProductType.ID;
            model.Code = txtCode.Text.Trim();
            model.Name = txtName.Text.Trim();
            model.NamePY = CommonControl.StringHelper.GetFirstLetterOfChinese(model.Name, true);
            model.FullName = txtFullName.Text.Trim();
            model.Specification = txtSpecification.Text.Trim();
            model.Model = txtModel.Text.Trim();
            model.UnitID = lueUnit.EditValue == null ? 0 : Convert.ToInt32(lueUnit.EditValue);
            model.UnitID1 = lueUnit1.EditValue == null ? 0 : Convert.ToInt32(lueUnit1.EditValue);
            model.ChangeRate = speChangeRate.Value;
            model.IsStop = chkIfStop.Checked;
            model.Remark = mmeRemark.Text;

            ProcessesResult(bll.AddExpand(model));
        }

        /// <summary>
        /// 处理保存结果
        /// </summary>
        /// <param name="result"></param>
        private void ProcessesResult(long result)
        {
            if (result > 0)
            {
                XtraMessageBox.Show("保存成功。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                ID = result;
                LoadData();
            }
            else
            {
                if (result == -1000)
                {
                    XtraMessageBox.Show("编号重复。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtCode.Focus();
                    txtCode.SelectAll();
                }
                else
                {
                    if (result == -1001)
                    {
                        XtraMessageBox.Show("该产品类型不存在。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        bteProductTypeNo.Focus();
                        bteProductTypeNo.SelectAll();
                    }
                    else
                    {
                        if (result == -1002)
                        {
                            XtraMessageBox.Show("单位不存在。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            lueUnit.Focus();
                        }
                        else
                        {
                            if (result == -1003)
                            {
                                XtraMessageBox.Show("辅助单位不存在。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                                bteProductTypeNo.Focus();
                                bteProductTypeNo.SelectAll();
                            }
                            else
                            {
                                ID = result;
                                LoadData();
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 验证输入
        /// </summary>
        /// <returns></returns>
        private bool ValidateInput()
        {
            if (ProductType == null)
            {
                if (bteProductTypeNo.Text.Trim().Length > 0)
                {
                    XtraMessageBox.Show("输入类型编号后，请回车确认。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    bteProductTypeNo.Focus();
                    return false;
                }
                else
                {
                    XtraMessageBox.Show("请输入类型编号。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    bteProductTypeNo.Focus();
                    return false;
                }
            }
            else
            {
                if (txtCode.Text.Trim().Length == 0)
                {
                    XtraMessageBox.Show("请输入产品编号。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    txtCode.Focus();
                    return false;
                }
                else
                {
                    if (txtName.Text.Trim().Length == 0)
                    {
                        XtraMessageBox.Show("请输入产品名称。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                        txtName.Focus();
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 验证产品类型
        /// </summary>
        /// <returns></returns>
        private bool ValidateProductType()
        {
            if (bteProductTypeNo.Text.Trim().Length == 0)
            {
                ProductType = null;
                return true;
            }

            var bll = new DMZS.BLL.ProductType();
            var model = bll.GetModel(bteProductTypeNo.Text.Trim());
            if (model == null)
            {
                XtraMessageBox.Show("该产品类型不存在。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                bteProductTypeNo.Focus();
                bteProductTypeNo.SelectAll();
                return false;
            }
            else
            {
                ProductType = model;
                return true;
            }
        }

        #endregion ================================功能函数区=====================================


        #region ================================工具栏按钮事件=====================================

        //第一条
        private void btnFirst_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var bll = new DMZS.BLL.Product();
            var row = bll.GetFirst();
            if (row != null)
            {
                ID = Convert.ToInt64(row["ID"]);
                LoadData();
            }
            else
            {
                NewRecord();
            }
        }

        //上一条
        private void btnPrevious_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ID <= 0)
            {
                return;
            }
            var bll = new DMZS.BLL.Product();
            var row = bll.GetPrevious(ID);
            if (row != null)
            {
                ID = Convert.ToInt64(row["ID"]);
                LoadData();
            }
            else
            {
                LoadData();
            }
        }

        //下一条
        private void btnNext_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ID <= 0)
            {
                return;
            }
            var bll = new DMZS.BLL.Product();
            var row = bll.GetNext(ID);
            if (row != null)
            {
                ID = Convert.ToInt64(row["ID"]);
                LoadData();
            }
            else
            {
                LoadData();
            }
        }

        //最后条
        private void btnLast_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var bll = new DMZS.BLL.Product();
            var row = bll.GetLast();
            if (row != null)
            {
                ID = Convert.ToInt64(row["ID"]);
                LoadData();
            }
            else
            {
                NewRecord();
            }
        }

        //新增
        private void btnNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            NewRecord();
        }

        //保存
        private void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            txtCode.Focus();
            if (!ValidateInput())
            {
                return;
            }
            if (ID <= 0)
            {
                SavaNew();
            }
            else
            {
                SaveModify();
            }
        }

        //删除
        private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ID <= 0)
            {
                NewRecord();
            }
            else
            {
                if (DialogResult.Yes == XtraMessageBox.Show("确认删除?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1))
                {
                    var bll = new DMZS.BLL.Product();
                    if (bll.DeleteExpand(ID))
                    {
                        NewRecord();
                    }
                    else
                    {
                        XtraMessageBox.Show("该产品已被引用,无法删除。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }

        //刷新
        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            LoadInit();
            if (ID <= 0)
            {
                NewRecord();
            }
            else
            {
                LoadData();
            }
        }

        #endregion ================================工具栏按钮事件=====================================


        #region ================================单位下拉框按钮事件=====================================
        private void lueUnit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var lue = sender as GridLookUpEdit;
            switch (e.Button.Kind)
            {
                case DevExpress.XtraEditors.Controls.ButtonPredefines.Delete:
                    lue.ClosePopup();
                    lue.Text = "";
                    lue.EditValue = null;
                    break;
                case DevExpress.XtraEditors.Controls.ButtonPredefines.Combo:
                    lue.ShowPopup();
                    break;
            }
        }
        #endregion ================================单位下拉框按钮事件=====================================


        #region ================================产品类别输入框事件=====================================
        //焦点进入
        private void bteProductTypeNo_Enter(object sender, EventArgs e)
        {
            bteProductTypeNo.Text = ProductType == null ? "" : ProductType.Code;
        }

        //焦点离开
        private void bteProductTypeNo_Leave(object sender, EventArgs e)
        {
            bteProductTypeNo.Text = ProductType == null ? "" : ProductType.Name;
        }

        //监听回车
        private void bteProductTypeNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                if (ValidateProductType()) SendKeys.Send("{TAB}");
            }
        }

        //产品类别输入框按钮事件
        private void bteProductTypeNo_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var frm = new DialogForm.FrmProductType_dlg();
            frm.ReturnList += new DialogForm.FrmProductType_dlg.ReturnListEventHandler(frm_ReturnList);
            frm.ShowDialog();
        }

        /// <summary>
        /// 产品类别对话框选择 处理
        /// </summary>
        /// <param name="lists"></param>
        void frm_ReturnList(List<DataRow> lists)
        {
            if (lists.Count == 0) return;

            var bll = new DMZS.BLL.ProductType();
            var model = bll.GetModel(Convert.ToInt64(lists[0]["ID"]));
            if (model != null)
            {
                ProductType = model;
                bteProductTypeNo.Text = model.Code;
            }
        }

        #endregion ================================产品类别输入框事件=====================================

    }
}
